<template>
  <div class="app-container table-app-container table-report">
    <div class="fixed-table">
      <div class="fixed-table-actionbar">
        <div class="search-bar">
          <el-form :inline="true" :model="formSearch" class="form-filter" size="mini" @submit.native.prevent>
            <el-form-item>
              <el-select v-model="formSearch.timeDim" filterable placeholder="时段" @change="fetch">
                <el-option v-for="(item) in timeDimList" :key="item.code" :label="item.text" :value="item.code" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="formSearch.timeDim==='day'">
              <el-date-picker v-model="formSearch.s_date" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" @change="fetch" />
            </el-form-item>
            <el-form-item v-if="formSearch.timeDim==='month'">
              <el-date-picker v-model="formSearch.s_date" type="month" placeholder="选择月" value-format="yyyy-MM" @change="fetch" />
            </el-form-item>
            <el-form-item v-if="formSearch.timeDim==='year'">
              <el-date-picker v-model="formSearch.s_date" type="year" placeholder="选择年" value-format="yyyy" @change="fetch" />
            </el-form-item>
          </el-form>
        </div>
        <div class="action-bar">
          <el-button type="text" @click="download('excel')"><el-image style="width: 16px; height: 16px" :src="excelIcon" fit="fill" /></el-button>
          <el-button type="text" @click="download('pdf')"><el-image style="width: 16px; height: 16px" :src="pdfIcon" fit="fill" /></el-button>
        </div>
      </div>
      <div class="title">省联社机关部门{{ title }}</div>
      <el-table
        v-loading="loading"
        border
        size="mini"
        show-summary
        :summary-method="getSummaries"
        :span-method="objectSpanMethod"
        :data="insideTableData"
        class="fixed-table-table"
      >
        <el-table-column type="index" width="50" label="序号" />
        <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :sortable="column.sortable" header-align="center" align="center">
          <template slot-scope="scope">
            <column-render :render="column.render" :row="scope.row" :column="column" />
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import databind from '@neu/biz-core/mixins/databind'
import belongs from '@neu/dcam-ui/mixins/belongs'
import { getToken } from '@neu/biz-core/utils/auth'
import { list, exportCommonReportExcel, exportCommonReportPdf } from '@neu/dcam-ui/api/assetStats'

const excelIcon = require('./image/excel.png')
const pdfIcon = require('./image/pdf.png')
const timeDimList = [
  { code: 'day', text: '按日' },
  { code: 'month', text: '按月' },
  { code: 'halfyear', text: '按半年度' },
  { code: 'year', text: '按年度' }
]

export default {
  name: 'AssetTimeDimReportPage',
  components: {
  },
  // 加入混入，使表格混入更多的api操作
  mixins: [databind, belongs],
  data() {
    return {
      formSearch: {
        timeDim: 'day',
        s_date: null
      },
      insideColumns: [
        { title: '时段（购置日期）', key: 'date',
          render: (h, params) => {
            let txt = params.row.date
            if (this.formSearch.timeDim === 'halfyear') {
              if (txt) {
                txt = txt.replace('-0', '上半年')
                txt = txt.replace('-1', '下半年')
              }
            }
            return h('span', txt)
          }
        },
        {
          title: '部门',
          key: 'depart_name'
        },
        {
          title: '类型',
          key: 'type_name'
        },
        {
          title: '数量',
          key: 'type_count'
        },
        {
          title: '金额（元）',
          key: 'amount'
        }
      ],
      dateRowSpanData: {},
      departRowSpanData: {},
      timeDimList,
      excelIcon,
      pdfIcon,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Authentication': getToken()
      }
    }
  },
  computed: {
    title: function() {
      if (this.categories === '1') {
        return '固定资产报表'
      } else if (this.categories === '2') {
        return '低值易耗品报表'
      } else if (this.categories === '3') {
        return '消耗品报表'
      } else {
        return '报表'
      }
    }
  },
  created() {
    this.fetch()
  },
  methods: {
    fetch() {
      this.loading = true
      const params = {}
      if (this.formSearch.s_date) {
        params.s_date = this.formSearch.s_date
      }
      list(this.categories, this.formSearch.timeDim, params).then(response => {
        this.insideTableData = this.responseFormatter(response.data)
      }).finally(() => {
        this.loading = false
      })
    },
    responseFormatter: function(data) {
      data.forEach(item => {
        if (item.amount !== undefined) {
          item.amount = item.amount.toFixed(2)
        }
      })
      this.setDateRowSpanData(data)
      this.setDepartRowSpanData(data)
      return data
    },
    setDateRowSpanData(data) {
      const dateRowSpanData = {}
      const tmp = {}
      for (let i = 0; i < data.length; i++) {
        if (!tmp[data[i].date]) {
          tmp[data[i].date] = [i, 1]
        } else {
          tmp[data[i].date][1] = tmp[data[i].date][1] + 1
        }
      }
      const arr = Object.values(tmp)
      for (let i = 0; i < arr.length; i++) {
        dateRowSpanData[arr[i][0]] = {
          rowspan: arr[i][1],
          colspan: 1
        }
      }
      this.dateRowSpanData = dateRowSpanData
    },
    setDepartRowSpanData(data) {
      const departRowSpanData = {}
      const tmp = {}
      for (let i = 0; i < data.length; i++) {
        const key = data[i].date + data[i].depart_name
        if (!tmp[key]) {
          tmp[key] = [i, 1]
        } else {
          tmp[key][1] = tmp[key][1] + 1
        }
      }
      const arr = Object.values(tmp)
      for (let i = 0; i < arr.length; i++) {
        departRowSpanData[arr[i][0]] = {
          rowspan: arr[i][1],
          colspan: 1
        }
      }
      this.departRowSpanData = departRowSpanData
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        if (this.dateRowSpanData[rowIndex]) {
          return this.dateRowSpanData[rowIndex]
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      } else if (columnIndex === 2) {
        if (this.departRowSpanData[rowIndex]) {
          return this.departRowSpanData[rowIndex]
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (index === 2 || index === 3) {
          sums[index] = ''
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        }
        if (index === 4) {
          if (sums[index] !== undefined) {
            sums[index] = sums[index].toFixed(2)
          }
        }
      })
      return sums
    },
    download(contentType) {
      const API = contentType === 'excel' ? exportCommonReportExcel : exportCommonReportPdf
      const params = {}
      if (this.formSearch.s_date) {
        params.s_date = this.formSearch.s_date
      }
      this.loading = true
      API(this.categories, this.formSearch.timeDim)(params).then(response => {
        this.loading = false
        const content = response.data
        const fileName = response.headers['content-disposition'].split('filename=')[1]
        const blob = new Blob([content])
        // const fileName = '导出信息.xlsx'
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = decodeURIComponent(fileName)
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      })
    }
  }
}
</script>

<style lang="scss">
  .table-report {
    padding: 40px;
    .title {
      text-align: center;
      margin-bottom: 20px;
      font-size: 24px;
    }
    .el-table th {
      background-color: rgb(217,234,211);
      color: #000000;
      border-bottom: 1px solid #aeb2b5;
    }

    .el-table thead.is-group th {
      background: rgb(217,234,211);
    }

    .el-table--border th, .el-table--border td {
      border-right: 1px solid #aeb2b5;
    }
    .el-table td {
      border-bottom: 1px solid #aeb2b5;
    }

    .el-table--border {
      border-bottom: 1px solid #aeb2b5;
    }
  }

  .table-app-container .fixed-table .el-table th {
    border-top: 1px solid #aeb2b5;
  }

  .table-app-container .fixed-table .el-table {
    border-left: 1px solid #aeb2b5;
    border-right: 1px solid #aeb2b5;
  }
</style>
